package com.wasp.collector.timer;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wasp.collector.utils.PropertiesUtil;
import com.wasp.collector.utils.ResourceException;
public class QuartzManager{
	private static final Logger log = LoggerFactory.getLogger(QuartzManager.class);

	private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	private static String JOB_GROUP_NAME = "WEBCOLLECTOR_JOBGROUP_NAME";
	private static String TRIGGER_GROUP_NAME = "WEBCOLLECTOR_TRIGGERGROUP_NAME";
	private static QuartzManager manager;
	private QuartzManager() throws Exception{
		init();
	}
	public static QuartzManager build() throws Exception{
		if(manager == null){
			synchronized (JOB_GROUP_NAME) {
				if(manager == null){
					manager = new QuartzManager();
				}
			}
		}
		return manager;
	}
	public void addJob(JobEntity entity){
		JobDetail job = newJob(entity.getClassz())
				.withIdentity(entity.getJobName(), JOB_GROUP_NAME).build();

	    Trigger trigger = newTrigger().withIdentity(entity.getTriggerName(),
	    		TRIGGER_GROUP_NAME).withSchedule(cronSchedule(entity.getConExpression()))
	            .build();

	    Scheduler sched;
		try {
			sched = gSchedulerFactory.getScheduler();
			sched.scheduleJob(job, trigger);
			if(!sched.isStarted()){
				sched.start();
			}
		} catch (SchedulerException e) {
			log.error("add job",e);
		}
	    // schedule the job to run
	}
	/**
	 * 服务器启动，加载job_status=1的任务到任务队列中
	 * 
	 * @throws Exception
	 */
	@PostConstruct
	private void init() throws Exception {

		// 这里获取任务信息数据
		List<JobEntity> listEntities = findAllJobs();
		if(listEntities != null){
			listEntities.stream().forEach(entity->addJob(entity));
		}
	}

	

	/**
	 * 删除一个job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void deleteJob(JobEntity entity) throws SchedulerException {
		Scheduler scheduler = gSchedulerFactory.getScheduler();
		JobKey jobKey = JobKey.jobKey(entity.getJobName(), JOB_GROUP_NAME);
		scheduler.deleteJob(jobKey);
	}


	/**
	 * 更新job时间表达式
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void updateJobCron(JobEntity entity) throws SchedulerException {
		Scheduler scheduler = gSchedulerFactory.getScheduler();

		TriggerKey triggerKey = TriggerKey.triggerKey(entity.getJobName(), JOB_GROUP_NAME);

		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(entity.getConExpression());

		trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

		scheduler.rescheduleJob(triggerKey, trigger);
	}
	
	private List<JobEntity> findAllJobs() throws ResourceException{
		return PropertiesUtil.loadJobs();
		
	}
}
